package com.example.teamtribe.main.club;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.CallbackStore;
import com.example.teamtribe.common.model.FileModel;
import com.example.teamtribe.common.model.UserModel;
import com.example.teamtribe.database.Posting;
import com.example.teamtribe.json.JsonPosting;
import com.example.teamtribe.utils.HttpUtil;
import com.example.teamtribe.utils.URLStore;
import com.google.gson.Gson;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostingModel {

    private static PostingModel instance;
    private PostingModel() {}
    public static PostingModel getInstance() {
        if (instance == null) {
            synchronized (PostingModel.class) {
                if (instance == null) {
                    instance = new PostingModel();
                }
            }
        }
        return instance;
    }

    /***
     * @param title 评论的 title 必须为空
     * @param targetId 如果是帖子，该参数为0，如果为评论，该参数为评论的对象id
     */
    public void post(String token, int teamId, String title, String content, int targetId, List<String> fileNames, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("TeamTribeToken", token);
        params.put("teamId", teamId + "");
        if (title != null) {
            params.put("title", title);
        }
        StringBuilder builder = new StringBuilder(escape(content));
        if (fileNames != null && !fileNames.isEmpty()) {
            for (String string : fileNames) {
                builder.append('&').append(string);
            }
        }
        params.put("content", builder.toString());
        params.put("targetId", targetId + "");
        HttpUtil.post(URLStore.POST_ADD, params, CallbackStore.getIdCallback(back));
    }

    public void setTag(String token, int postId, int tagId, final Back back) {
        Map<String, String> params = new HashMap<>(3);
        params.put("TeamTribeToken", token);
        params.put("postId", postId + "");
        params.put("tagId", tagId + "");
        HttpUtil.post(URLStore.POST_TAG_ADD, params, CallbackStore.getCallback(back));
    }

    /**
     *
     * @param mode 0获取team的帖子，1获取user的帖子，2获取评论
     * @param id team或user或post的id
     * @param offset 起始位置（0开始）
     * @param num 几条记录
     */
    public void getPostingIds(int mode, final int id, int offset, int num, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        params.put("offset", offset + "");
        params.put("num", num + "");
        String url;
        switch (mode) {
            case 0:url = URLStore.POST_GET_TEAM;break;
            case 1:url = URLStore.POST_GET_USER;break;
            case 2:url = URLStore.POST_GET_POST;break;
            default:throw new IllegalArgumentException("无效模式");
        }
        HttpUtil.post(url, params, CallbackStore.getIdsCallback(back));
    }

    public void getPostings(int mode, final int id, int offset, int num, final Back back) {
        getPostingIds(mode, id, offset, num, new Back() {
            ArrayList<Posting> postings = new ArrayList<>();
            Bundle bundle1 = new Bundle();
            @Override
            public void success(@Nullable Bundle bundle) {
                final List<Integer> ids = bundle.getIntegerArrayList("ids");
                if (ids == null || ids.isEmpty()) {
                    bundle1.putParcelableArrayList("postings", null);
                    back.success(bundle1);
                }
                for (int i : ids) {
                    getPosting(i, new Back() {
                        @Override
                        public void success(@Nullable Bundle bundle) {
                            Posting posting = bundle.getParcelable("posting");
                            //posting.saveOrUpdate();
                            postings.add(posting);
                            if (postings.size() == ids.size()) {
                                bundle1.putParcelableArrayList("postings", postings);
                                back.success(bundle1);
                            }
                        }

                        @Override
                        public void failure(String meg) {
                            back.failure(meg);
                        }
                    });
                }
            }

            @Override
            public void failure(String meg) {
                back.failure(meg);
            }
        });
    }

    public void getPosting(final int id, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        HttpUtil.post(URLStore.POST_GET, params, new CallbackStore.CallbackImpl<Back>(back) {
            @Override
            public void onResponse(String json) {
                Log.d("帖子", json);
                JsonPosting jsonPosting = new Gson().fromJson(json, JsonPosting.class);

                final Posting posting = jsonPosting.getPosting();
                String content = posting.getContent();
                String[] strings = content.split("&");
                posting.setContent(unescape(strings[0]));

                List<String> images = new ArrayList<>(Arrays.asList(strings));
                images.remove(0);
                posting.setImages(images);

                getHostId(id, new Back() {
                    @Override
                    public void success(@Nullable Bundle bundle) {
                        posting.setUserId(bundle.getInt("id"));
                        bundle.putParcelable("posting", posting);
                        back.success(bundle);
                    }

                    @Override
                    public void failure(String meg) {
                        back.failure(meg);
                    }
                });
            }
        });
    }

    public void deletePost(String token, int id, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        HttpUtil.post(URLStore.POST_DELTE, params, CallbackStore.getCallback(back));
    }

    public List<Posting> getLocalPostings(int mode, int id) {
        if (mode == 0)
            return DataSupport.where("teamId = ?", id + "").find(Posting.class);
        return DataSupport.where("userId = ?", id + "").find(Posting.class);
    }

    public void clearLocalPostings() {
        DataSupport.deleteAll(Posting.class);
    }

    public void getHostId(int id, final Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        HttpUtil.post(URLStore.POST_USER, params, CallbackStore.getIdCallback(back));
    }

    public void getHost(final String token, int id, final FileModel.FileBack back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        HttpUtil.post(URLStore.POST_USER, params, CallbackStore.getIdCallback(new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                UserModel.getInstance().getUser(token, bundle.getInt("id"), back);
            }

            @Override
            public void failure(String meg) {
                back.failure(meg);
            }
        }));
    }

    public void getTeamId(int postId, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("id", postId + "");
        HttpUtil.post(URLStore.POST_TEAM, params, CallbackStore.getIdCallback(back));
    }

    public String escape(String content) {
        content = content.replace("\"", "&quot;");
        content = content.replace("<", "&lt;");
        content = content.replace(">", "&gt;");
        content = content.replace(" ", "&nbsp;");
        content = content.replace("&", "&amp;");
        return content;
    }

    public String unescape(String content) {
        content = content.replace("&amp;", "&");
        content = content.replace("&nbsp;", " ");
        content = content.replace("&gt;", ">");
        content = content.replace("&lt;", "<");
        content = content.replace("&quot;", "\"");
        return content;
    }
}
